<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录 - CPPSearch</title>
    <link rel="stylesheet" href="css/styles.css">
    <style>
        /* 模态弹窗背景遮罩 */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            pointer-events: none; /* 完全禁用背景的鼠标事件 */
        }
        
        /* 模态弹窗容器 */
        .modal-container {
            position: relative;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.3);
            max-width: 400px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            pointer-events: auto; /* 重新启用容器的鼠标事件 */
            user-select: none; /* 防止文本选择 */
        }
        
        /* 关闭按钮 */
        .close-btn {
            position: absolute;
            top: 15px;
            right: 15px;
            width: 30px;
            height: 30px;
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            color: #6c757d;
            transition: all 0.3s ease;
            z-index: 10;
        }
        
        .close-btn:hover {
            background: #e9ecef;
            color: #495057;
            transform: scale(1.1);
        }
        
        .login-container {
            padding: 40px 40px 30px 40px;
        }
        
        .login-form {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        
        .form-group label {
            font-weight: bold;
            color: #333;
        }
        
        .form-group input {
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        .form-group input:focus {
            outline: none;
            border-color: #007bff;
        }
        
        .login-btn {
            background: #007bff;
            color: white;
            border: none;
            padding: 15px;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .login-btn:hover {
            background: #0056b3;
        }
        
        .login-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        
        .register-link {
            text-align: center;
            margin-top: 20px;
        }
        
        .register-link a {
            color: #007bff;
            text-decoration: none;
        }
        
        .register-link a:hover {
            text-decoration: underline;
        }
        
        .error-message {
            color: #dc3545;
            text-align: center;
            margin-top: 10px;
            display: none;
        }
        
        .success-message {
            color: #28a745;
            text-align: center;
            margin-top: 10px;
            display: none;
        }
        
        /* 防止页面滚动 */
        body.modal-open {
            overflow: hidden;
        }
    </style>
</head>
<body>
    <!-- 模态弹窗 -->
    <div class="modal-overlay" id="loginModal">
        <div class="modal-container">
            <!-- 关闭按钮 -->
            <button class="close-btn" id="closeBtn" title="关闭">×</button>
            
            <div class="login-container">
                <h2 style="text-align: center; margin-bottom: 30px;">用户登录</h2>
                <form id="loginForm" class="login-form">
                    <div class="form-group">
                        <label for="username">用户名</label>
                        <input type="text" id="username" name="username" required placeholder="请输入用户名">
                    </div>
                    <div class="form-group">
                        <label for="password">密码</label>
                        <input type="password" id="password" name="password" required placeholder="请输入密码">
                    </div>
                    <button type="submit" class="login-btn" id="loginBtn">登录</button>
                </form>
                
                <!-- 登录后跳转选项 -->
                <div class="redirect-options" style="margin-top: 20px; text-align: center;">
                    <label style="font-size: 14px; color: #666;">登录后跳转到：</label>
                    <div style="margin-top: 10px;">
                        <label style="margin-right: 15px;">
                            <input type="radio" name="redirect" value="index" checked> 首页
                        </label>
                        <label>
                            <input type="radio" name="redirect" value="user_center"> 用户中心
                        </label>
                    </div>
                </div>
                
                <div class="error-message" id="errorMessage"></div>
                <div class="success-message" id="successMessage"></div>
                <div class="register-link">
                    <p>还没有账号？<a href="register.html">立即注册</a></p>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 防止误触关闭的变量
        let isProcessing = false;
        
        // 关闭模态窗口函数
        function closeModal() {
            const modal = document.getElementById('loginModal');
            modal.style.display = 'none';
            document.body.classList.remove('modal-open');
            
            // 如果是在弹窗环境中，可以通知父窗口
            if (window.parent && window.parent !== window) {
                window.parent.postMessage({type: 'loginClosed'}, '*');
            } else {
                // 如果是独立页面，跳转到首页
                window.location.href = 'index.html';
            }
        }
        
        // 只阻止背景遮罩的点击事件
        const modal = document.getElementById('loginModal');
        modal.addEventListener('click', function(e) {
            // 如果点击的是背景本身（不是容器），阻止关闭
            if (e.target === modal) {
                e.preventDefault();
                e.stopPropagation();
                return false;
            }
        });
        
        // 关闭按钮事件 - 唯一可关闭的方式
        document.getElementById('closeBtn').addEventListener('click', function(e) {
            if (!isProcessing) {
                closeModal();
            }
        });
        
        // 阻止ESC键关闭弹窗
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                e.preventDefault();
                e.stopPropagation();
                return false;
            }
        });
        
        // 阻止右键菜单
        document.addEventListener('contextmenu', function(e) {
            e.preventDefault();
            return false;
        });
        
        document.getElementById('loginForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            if (isProcessing) return;
            
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const loginBtn = document.getElementById('loginBtn');
            const errorMessage = document.getElementById('errorMessage');
            const successMessage = document.getElementById('successMessage');
            
            // 重置消息
            errorMessage.style.display = 'none';
            successMessage.style.display = 'none';
            
            // 验证输入
            if (!username || !password) {
                errorMessage.textContent = '请填写完整的登录信息';
                errorMessage.style.display = 'block';
                return;
            }
            
            // 设置处理状态
            isProcessing = true;
            
            // 禁用登录按钮和关闭按钮
            loginBtn.disabled = true;
            loginBtn.textContent = '登录中...';
            document.getElementById('closeBtn').disabled = true;
            document.getElementById('closeBtn').style.cursor = 'not-allowed';
            
            try {
                const response = await fetch('/api/user/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        username: username,
                        password: password
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    successMessage.textContent = '登录成功，正在跳转...';
                    successMessage.style.display = 'block';
                    
                    // 保存用户信息到localStorage - 使用与首页一致的键名
                    const userInfo = {
                        username: username,
                        user_id: result.user_id || result.user?.user_id
                    };
                    localStorage.setItem('currentUser', JSON.stringify(userInfo));
                    localStorage.setItem('sessionId', result.session_id);
                    
                    // 获取用户选择的跳转目标
                    const redirectTarget = document.querySelector('input[name="redirect"]:checked').value;
                    
                    // 延迟跳转
                    setTimeout(() => {
                        if (window.parent && window.parent !== window) {
                            // 在弹窗环境中，通知父窗口登录成功
                            window.parent.postMessage({
                                type: 'loginSuccess',
                                user: userInfo,
                                sessionId: result.session_id,
                                redirect: redirectTarget
                            }, '*');
                        } else {
                            // 独立页面，根据选择跳转
                            if (redirectTarget === 'user_center') {
                                window.location.href = 'user_center.html';
                            } else {
                                window.location.href = 'index.html';
                            }
                        }
                    }, 1500);
                } else {
                    errorMessage.textContent = result.message || '登录失败，请检查用户名和密码';
                    errorMessage.style.display = 'block';
                }
            } catch (error) {
                errorMessage.textContent = '网络错误，请稍后重试';
                errorMessage.style.display = 'block';
                console.error('Login error:', error);
            } finally {
                // 恢复按钮状态
                isProcessing = false;
                loginBtn.disabled = false;
                loginBtn.textContent = '登录';
                document.getElementById('closeBtn').disabled = false;
                document.getElementById('closeBtn').style.cursor = 'pointer';
            }
        });
        
        // 输入框焦点效果
        document.getElementById('username').addEventListener('input', function() {
            document.getElementById('errorMessage').style.display = 'none';
        });
        
        document.getElementById('password').addEventListener('input', function() {
            document.getElementById('errorMessage').style.display = 'none';
        });
        
        // 检查是否已登录
        window.addEventListener('load', function() {
            const user = localStorage.getItem('currentUser');
            if (user) {
                // 如果已登录，直接跳转到首页
                if (window.parent && window.parent !== window) {
                    window.parent.postMessage({
                        type: 'loginSuccess',
                        user: JSON.parse(user),
                        sessionId: localStorage.getItem('sessionId')
                    }, '*');
                } else {
                    window.location.href = 'index.html';
                }
            } else {
                // 显示模态窗口
                document.body.classList.add('modal-open');
            }
        });
    </script>
</body>
</html>